{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quick and dirty keywords from small texts with spaCy\n",
    "\n",
    "By [Allison Parrish](http://www.decontextualize.com/)\n",
    "\n",
    "The idea of \"keyword extraction\" goes by a number of names, depending on your field of study (\"keyphrase selection,\" \"lexical feature selection,\" \"automatic terms recognition\"), but the basic idea is the same: for a given text, find the words in the text that are most representative of what that text is about.\n",
    "\n",
    "I wanted to figure out a performant and elegant way to do keyword extraction that works well on individual texts of small to medium size (like individual poems), is fairly easy to explain and reason about, doesn't require tweaking but is easy to tweak if necessary, and doesn't require any external data or libraries outside of [spaCy](https://spacy.io/) and what you get by default with Anaconda. This notebook shows a solution I found that meets these criteria.\n",
    "\n",
    "## Keyword extraction\n",
    "\n",
    "There's enough academic literature about keyword extraction that someone could easily write a survey article about all of the survey articles. These two overviews were the most helpful for me in understanding the scope of the problem and formulating a solution:\n",
    "\n",
    "* Astrakhantsev, N. “ATR4S: Toolkit with State-of-the-Art Automatic Terms Recognition Methods in Scala.” ArXiv:1611.07804 [Cs], Nov. 2016. arXiv.org, http://arxiv.org/abs/1611.07804.\n",
    "* [Chuang, Jason, et al. “‘Without the Clutter of Unimportant Words’: Descriptive Keyphrases for Text Visualization.” ACM Transactions on Computer-Human Interaction (TOCHI), vol. 19, no. 3, 2012, p. 19.](http://vis.stanford.edu/papers/keyphrases)\n",
    "\n",
    "Here's an outline of the solution I came up with:\n",
    "\n",
    "* Tokenize the source text with spaCy\n",
    "* Compute the observed frequency of each token in the source text\n",
    "* Calculate the expected frequency of each token using spaCy's built-in unigram probabilities\n",
    "* Find the significance of the difference between observed and expected frequency using a [G-test](https://en.wikipedia.org/wiki/G-test) (as implemented with scipy's `chi2_contingency` function)\n",
    "* Return the tokens with the highest significance\n",
    "\n",
    "To be clear, the approach of using a likelihood ratio test to measure keyness is nothing new (see below for Dunning's proposal from 1993!). The only real trick in my implementation is using spaCy's unigram probabilities as the \"reference corpus.\"\n",
    "\n",
    "## Implementation\n",
    "\n",
    "First, import spacy and load the model. (You need the medium model or the large model for this to work; the small model doesn't come with accurate probability information.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import spacy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "nlp = spacy.load('en_core_web_md')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the following few cells, I pasted in verbatim some small documents to test the procedure on."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "genesis_txt = \"\"\"\\\n",
    "In the beginning God created the heaven and the earth. \n",
    "And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters. \n",
    "And God said, Let there be light: and there was light. \n",
    "And God saw the light, that it was good: and God divided the light from the darkness. \n",
    "And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day. \n",
    "And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters. \n",
    "And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so. \n",
    "And God called the firmament Heaven. And the evening and the morning were the second day. \n",
    "And God said, Let the waters under the heaven be gathered together unto one place, and let the dry land appear: and it was so. \n",
    "And God called the dry land Earth; and the gathering together of the waters called he Seas: and God saw that it was good. \n",
    "And God said, Let the earth bring forth grass, the herb yielding seed, and the fruit tree yielding fruit after his kind, whose seed is in itself, upon the earth: and it was so. \n",
    "And the earth brought forth grass, and herb yielding seed after his kind, and the tree yielding fruit, whose seed was in itself, after his kind: and God saw that it was good. \n",
    "And the evening and the morning were the third day. \n",
    "And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years: \n",
    "And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so. \n",
    "And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: he made the stars also. \n",
    "And God set them in the firmament of the heaven to give light upon the earth, \n",
    "And to rule over the day and over the night, and to divide the light from the darkness: and God saw that it was good. \n",
    "And the evening and the morning were the fourth day. \n",
    "And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl that may fly above the earth in the open firmament of heaven. \n",
    "And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that it was good. \n",
    "And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth. \n",
    "And the evening and the morning were the fifth day. \n",
    "And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so. \n",
    "And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that it was good. \n",
    "And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth. \n",
    "So God created man in his own image, in the image of God created he him; male and female created he them. \n",
    "And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth. \n",
    "And God said, Behold, I have given you every herb bearing seed, which is upon the face of all the earth, and every tree, in the which is the fruit of a tree yielding seed; to you it shall be for meat. \n",
    "And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein there is life, I have given every green herb for meat: and it was so. \n",
    "And God saw every thing that he had made, and, behold, it was very good. And the evening and the morning were the sixth day. \n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "frost_txt = \"\"\"\\\n",
    "Two roads diverged in a yellow wood,\n",
    "And sorry I could not travel both\n",
    "And be one traveler, long I stood\n",
    "And looked down one as far as I could\n",
    "To where it bent in the undergrowth;\n",
    "\n",
    "Then took the other, as just as fair,\n",
    "And having perhaps the better claim,\n",
    "Because it was grassy and wanted wear;\n",
    "Though as for that the passing there\n",
    "Had worn them really about the same,\n",
    "\n",
    "And both that morning equally lay\n",
    "In leaves no step had trodden black.\n",
    "Oh, I kept the first for another day!\n",
    "Yet knowing how way leads on to way,\n",
    "I doubted if I should ever come back.\n",
    "\n",
    "I shall be telling this with a sigh\n",
    "Somewhere ages and ages hence:\n",
    "Two roads diverged in a wood, and I —\n",
    "I took the one less travelled by,\n",
    "And that has made all the difference.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "hd_txt = \"\"\"\\\n",
    "Rose, harsh rose, \n",
    "marred and with stint of petals, \n",
    "meagre flower, thin, \n",
    "spare of leaf,\n",
    "\n",
    "more precious \n",
    "than a wet rose \n",
    "single on a stem -- \n",
    "you are caught in the drift.\n",
    "\n",
    "Stunted, with small leaf, \n",
    "you are flung on the sand, \n",
    "you are lifted \n",
    "in the crisp sand \n",
    "that drives in the wind.\n",
    "\n",
    "Can the spice-rose \n",
    "drip such acrid fragrance \n",
    "hardened in a leaf?\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using spaCy to calculate the expected count of a token\n",
    "\n",
    "Using spaCy's unigram probabilities, you can guess at how probable a given token is to appear in any given English text. The problem is that spaCy gives us the unigram probabilities in log form, but in order to calculate the G-test, we need an absolute count both of the token frequency *and* the total number of words in the reference corpus. My solution to this was to just... guess at the total number of tokens, and return numbers based on that guess. The `expected()` function below performs this operation. It takes a spaCy `Language` object and a word to look up and returns (as a tuple) the number of times the token is expected to occur and the size of the reference corpus that this guess is based on. (You can override the assumed total number of tokens by passing the named parameter `assumed_total`.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from math import e\n",
    "def expected(nlp, word, assumed_total=1e7):\n",
    "    guess = (e**nlp.vocab[word].prob) * assumed_total\n",
    "    return (guess, assumed_total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The call below shows us that the token `cat` is expected to occur around 735 times out of every ten million words:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(735.454676714558, 10000000.0)"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "expected(nlp, \"cat\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Whereas the token `the` occurs nearly three hundred thousand times:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(293410.81908600265, 10000000.0)"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "expected(nlp, \"the\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Counting observed tokens\n",
    "\n",
    "I'm using the first chapter of the King James Version of the Book of Genesis in the code below. The first step is to parse the text with spaCy so we can get a list of tokens:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "genesis_doc = nlp(genesis_txt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then I use Python's built-in `Counter` object to count the number of times each token occurs in the text and get the total number of tokens:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from collections import Counter\n",
    "observed = Counter([item.text for item in genesis_doc])\n",
    "observed_total = sum(observed.values())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Simple enough!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## G-test with scipy\n",
    "\n",
    "For our purposes, you can think of a [G-test](https://en.wikipedia.org/wiki/G-test) as a way of determining whether the difference in token counts between two corpora is significant or not, based on the size of the corpora in question. The likelihood ratio calculation used here was originally proposed in the following paper:\n",
    "\n",
    "* Dunning, Ted. “Accurate Methods for the Statistics of Surprise and Coincidence.” Computational Linguistics, vol. 19, no. 1, 1993, pp. 61–74.\n",
    "\n",
    "Ted Dunning [wrote an informative blog post about the method here](https://tdunning.blogspot.com/2008/03/surprise-and-coincidence.html) and also maintains [a GitHub repository with an implementation of the log-likelihood ratio in question](https://github.com/tdunning/python-llr).\n",
    "\n",
    "I'm going to use the `scipy.stats` library, which has a function called `chi2_contingency` that implements the same likelihood function that Dunning describes. You give it a 2x2 matrix with the observed frequency of a token, the total number of observed tokens, the expected frequency of the token according to the reference corpus (spaCy's unigram probabilities, in our case), and the total number of tokens in the reference corpus. It returns the result of the G-test as the first item in a tuple:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(139.73209059296906,\n",
       " 3.0464897814259877e-32,\n",
       " 1,\n",
       " array([[  5.52243782e-03,   9.62994478e+02],\n",
       "        [  5.73464529e+01,   9.99998901e+06]]))"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy.stats import chi2_contingency\n",
    "chi2_contingency([(observed[\"waters\"], observed_total), expected(nlp, \"waters\")], lambda_=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following function performs this G-test on a word, given the `Counter` object for the text in question and the total number of tokens:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def spacygtest(nlp, ob_counts, ob_total, word, assumed_total=1e7):\n",
    "    g = chi2_contingency([[ob_counts[word], ob_total], expected(nlp, word)], lambda_=0)\n",
    "    return g[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The G-test says that the probability of `waters` is significantly different:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "139.73209059296906"
      ]
     },
     "execution_count": 152,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spacygtest(nlp, observed, observed_total, \"waters\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While the probability of `was` is less significant:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "16.32021435023545"
      ]
     },
     "execution_count": 154,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spacygtest(nlp, observed, observed_total, \"was\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Keywords at last\n",
    "\n",
    "With all of the above in mind, getting a list of keywords from our source text is a simple matter of sorting words in reverse order by the result of the G-test:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "scored = [(item, spacygtest(nlp, observed, observed_total, item)) for item in observed.keys()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('God', 264.28722467522732),\n",
       " ('earth', 198.04293506348199),\n",
       " ('And', 171.795604760217),\n",
       " ('firmament', 149.287711944471),\n",
       " ('waters', 139.73209059296906),\n",
       " ('the', 124.22752085499357),\n",
       " ('\\n', 101.79227284635938),\n",
       " ('fowl', 88.192035359442002),\n",
       " ('and', 80.254213997373384),\n",
       " ('upon', 77.033264373268906),\n",
       " ('yielding', 68.555046765251475),\n",
       " ('light', 63.50760252933739),\n",
       " ('seed', 56.44045670161627),\n",
       " ('heaven', 54.068266900441202),\n",
       " ('evening', 53.712557047220272)]"
      ]
     },
     "execution_count": 117,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted(scored, key=lambda x: x[1], reverse=True)[:15]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This list of words is perhaps a little unintuitive, since it includes words that you might not consider to be \"key,\" like `And` and `the` (and even the newline token `\\n`). But if you actually take a look at the original source text, I think you'll find that these words really *do* occur in the first chapter of Genesis in a way that is peculiar to that text.\n",
    "\n",
    "The `keyness()` function nicely wraps up the `spacygtest()` function. Pass it a spaCy `Language` object and a list of tokens, and you'll get back the tokens in order of their keyness:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def keyness(nlp, tokens):\n",
    "    observed = Counter(tokens)\n",
    "    observed_total = sum(observed.values())\n",
    "    scored = [(item, spacygtest(nlp, observed, observed_total, item)) for item in observed.keys()]\n",
    "    return sorted(scored, key=lambda x: x[1], reverse=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can filter and transform the tokens however you'd like before sending them to this function. For example, in the cell below, I convert every token to lowercase and filter out any tokens that aren't alphanumeric:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('god', 282.15227472985032),\n",
       " ('earth', 217.36279310994706),\n",
       " ('and', 210.96032879214761),\n",
       " ('firmament', 152.29209884772735),\n",
       " ('the', 151.26609219696854),\n",
       " ('waters', 143.43776984372414),\n",
       " ('fowl', 90.13927244329129),\n",
       " ('upon', 80.369633883611058),\n",
       " ('let', 73.736463442332791),\n",
       " ('yielding', 70.149066167234366)]"
      ]
     },
     "execution_count": 156,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keyness(nlp, [item.text.lower() for item in genesis_doc if item.is_alpha])[:10]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Quick, dirty, dead simple\n",
    "\n",
    "To make things even simpler, I made the `keywords()` function defined below. It takes a spaCy `Language` object and a string and evaluates to a list of ten keywords from that string, tokenizing it first with spaCy. You can also pass a named parameter `n` to the function to set the number of keywords to return."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def keywords(nlp, text, n=10, transform=None, filter_=None):\n",
    "    doc = nlp(text)\n",
    "    if transform is None:\n",
    "        transform = lambda x: x.text.lower()\n",
    "    if filter_ is None:\n",
    "        filter_ = lambda x: x.pos_ in ('NOUN', 'PROPN', 'ADJ')\n",
    "    tokens = [transform(item) for item in doc if filter_(item)]\n",
    "    scored = keyness(nlp, tokens)\n",
    "    return [item[0] for item in scored][:n]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Twelve keywords from Genesis:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['god',\n",
       " 'earth',\n",
       " 'firmament',\n",
       " 'waters',\n",
       " 'fowl',\n",
       " 'light',\n",
       " 'heaven',\n",
       " 'seed',\n",
       " 'evening',\n",
       " 'kind',\n",
       " 'day',\n",
       " 'morning']"
      ]
     },
     "execution_count": 158,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords(nlp, genesis_txt, n=12)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And from Robert Frost's \"The Road Not Taken\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['roads',\n",
       " 'ages',\n",
       " 'wood',\n",
       " 'undergrowth',\n",
       " 'grassy',\n",
       " 'traveler',\n",
       " 'way',\n",
       " 'sigh',\n",
       " 'yellow',\n",
       " 'passing',\n",
       " 'leaves',\n",
       " 'morning']"
      ]
     },
     "execution_count": 159,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords(nlp, frost_txt, n=12)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And from H.D.'s \"Sea Rose\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['rose',\n",
       " 'leaf',\n",
       " 'sand',\n",
       " 'acrid',\n",
       " 'meagre',\n",
       " 'petals',\n",
       " 'stunted',\n",
       " 'fragrance',\n",
       " 'stint',\n",
       " 'crisp',\n",
       " 'drift',\n",
       " 'spice']"
      ]
     },
     "execution_count": 160,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords(nlp, hd_txt, n=12)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, the `keywords()` function converts all words to lower case before processing, and only includes nouns, proper nouns and adjectives as candidate words. You can override these defaults with the named parameters `filter_` and `transform`, which allow you to pass in functions that will be used to filter out tokens and transform them before counting (respectively). The functions will be passed a single parameter, which is the `Token` object from the spaCy document. For example, to use the lemmas of the words instead of the words themselves:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['god',\n",
       " 'earth',\n",
       " '-PRON-',\n",
       " 'firmament',\n",
       " 'light',\n",
       " 'fowl',\n",
       " 'water',\n",
       " 'heaven',\n",
       " 'seed',\n",
       " 'evening']"
      ]
     },
     "execution_count": 139,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords(nlp, genesis_txt, n=10,\n",
    "         transform=lambda x: x.lemma_)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or to find only the keywords that are adjectives with seven or more characters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['beauteous',\n",
       " 'fairest',\n",
       " 'eternal',\n",
       " 'gracious',\n",
       " 'precious',\n",
       " 'sweetest',\n",
       " 'outward',\n",
       " 'mistress',\n",
       " 'strange',\n",
       " 'antique',\n",
       " 'forsworn',\n",
       " 'contented',\n",
       " 'virtuous',\n",
       " 'heavenly',\n",
       " 'sovereign',\n",
       " \"imprison'd\",\n",
       " \"unfather'd\",\n",
       " \"confin'd\",\n",
       " 'unrespected',\n",
       " 'outworn']"
      ]
     },
     "execution_count": 140,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keywords(nlp, open(\"sonnets.txt\").read(), n=20,\n",
    "         filter_=lambda x: x.pos_ == 'ADJ' and len(x.text) >= 7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A comparison\n",
    "\n",
    "I haven't tested this method of keyword extraction against any of the established benchmarks, but it seems to work pretty well in informal case studies (i.e., I think the results are pretty good). For the sake of comparison with other methods of keyword extraction, take a look at the results of using Gensim's `keywords` method (based on TextRank) on H.D.'s \"Sea Rose\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gensim.summarization import keywords as gensim_kw"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rose\n",
      "fragrance\n",
      "meagre\n"
     ]
    }
   ],
   "source": [
    "print(gensim_kw(hd_txt))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or \"The Road Not Taken\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "equally\n",
      "black\n",
      "wear\n"
     ]
    }
   ],
   "source": [
    "print(gensim_kw(frost_txt))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These results are admittedly cherry-picked, but I do think they're illustrative of the advantages of the approach outlined above."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
